Python Program to Reverse an Integer Number in 4 Best Methods for Interviews

Python program to reverse an integer using while loop and other methods


Hi friends welcome back to DailyCodeHub

When you start learning Python or preparing for coding interviews, one of the first problems you will see is reversing a number. many beginners think this is a very small problem and try to solve it quickly without understanding the logic.

This problem is very important.
It helps you understand how numbers are handled internally, how digits are extracted step by step and how loops work in real coding situations. once you understand this problem clearly many other problems like palindrome,sum of digits and armstrong numbers become very easy.

When i first learned this i knew how to write the code, but i could not explain why it works. after practicing slowly and understanding each step everything became clear.
 
So in this post i will explain this problem in a very simple way so that you can understand it easily and also explain it confidently in interviews.

Let us get started.

Before we start, let us understand the basics :

Reversing a number means changing the order of its digits.

for example :

Input: 1234
Output: 4321

This means we take digits from the right side and rebuild the numbers from the left side.

Another example :

Input: 560
Output: 65
Here the zero is removed because numbers do not keep leading zeros.

So the idea is simple:
  • Take the last digit
  • Add it to a new number
  • Repeat until the number becomes 0
Question :

Write a Python Program to reverse an integer number.

Method 1 : Using while loop | Level: Beginner | Best for : interviews

This is the most important method. every beginner must understand this clearly.

Code :

# Author: P.Prabhas

# Function to reverse number using while loop
def reverse_number(num):
    # Initialize reversed number
    reverse = 0
    # Loop until number becomes 0
    while num > 0:
        digit = num % 10 # Get last digit
        reverse = reverse * 10 + digit # Build reversed number
        num = num // 10 # Remove last digit
    return reverse

# Take input
num = int(input("Enter a number: "))

# Print result
print("Reversed number:", reverse_number(num))

Output:

Enter a number: 1234
Reversed number: 4321

How it works :

First we take a number from the user and store it in a variable. then we create another variable called reverse and set it to 0. this variable will store the final reversed number.

We use a while loop that runs until the number becomes 0. inside the loop we take the last digit of the number using num% 10. this gives us one digit at a time from the right side.

Then we add that digit to the reverse value. before adding we multiply the reverse by 10 so that the digits shift to the left and make space for the new digit.

After that we remove the last digit from the number using num // 10.

We repeat this process until all digits are processed and the number becomes 0.

Finally we print the reversed number.

This works because we rebuild the number step by step in reverse order.

Method 2 : Using String | Level : Beginner | Best for : Easy solution

This method is simple and useful for quick solutions.

Code :

# Author: P.Prabhas

# Function to reverse number using string method
def reverse_number(num):
    # Convert number to string and reverse using slicing
    return int(str(num)[::-1])

# Take input
num = int(input("Enter a number: "))

# Print result
print("Reversed number:", reverse_number(num))

Output:

Enter a number: 1234
Reversed number: 4321

How it works :

First we convert the number into a string using str(). this allows us to work with each digit easily.
Then we reverse the string using slicing [::-1] this means Python reads the string from end to start.
After that we convert the reversed string back into an integer using int().
Finally we print the reversed number.
This method is easy because Python handles the reversing in internally, but it does not show the logic.

Method 3 : Using recursion | Level : intermediate | Best for : understanding logic 

This method uses a function that calls itself

Code :

# Author: P.Prabhas

# Function to reverse number using recursion
def reverse_number(num, rev=0):
    # Base case
    if num == 0:
        return rev
    # Extract last digit
    digit = num % 10
    # Build reversed number
    rev = rev * 10 + digit
    # Recursive call
    return reverse_number(num // 10, rev)

# Take input
num = int(input("Enter a number: "))

# Print result
print("Reversed number:", reverse_number(num))

Output:

Enter a number: 123
Reversed number: 321

 How it works :

In this method, we create a function that calls itself repeatedly. This is called recursion.
We first check if the number becomes 0. If it becomes 0, we return the reversed value. This is the base condition that stops the recursion.
If we do not take the last digit, update the reversed value, and call the function again with the remaining number.
This continues until the number becomes 0.
Each function call processes one digit.

Method 4 : Handling Negative Numbers | Level : Important | Best for : Real programs
 
This method handles both positive and negative numbers.

Code :

# Author: P.Prabhas

# Function to reverse number with negative handling
def reverse_number(num):
    # Store sign
    sign = 1
    if num < 0:
        sign = -1
        num = abs(num)
    # Initialize reverse
    reverse = 0
    # Reverse logic
    while num > 0:
        reverse = reverse * 10 + num % 10
        num //= 10
    # Apply sign
    return reverse * sign

# Take input
num = int(input("Enter a number: "))

# Print result
print("Reversed number:", reverse_number(num))

Output:
Enter a number: -123
Reversed number: -321

How it works :

First we check whether the number is negative. if it is negative, we store the sign and convert the number into a positive value.
Then we reverse the number using the same logic as before.
Finally we multiply the reversed number with the stored sign.
This ensures correct results for both positive and negative numbers.

Methods summary table :

Method  Technique Level Best For
While Loop Logic Beginner Interviews
String Slicing Beginner Easy
Recursion Function Intermediate Concept
Negative Handling Real case Important Practical

You can also read this:

Frequently asked questions :

Q. What is reversing a number?
A) Changing the order of digits

Q) Which method is best?
A) While loop

Q) Can we use string method?
A) Yes

Q) Why is this question important?
A) It builds logic

Q) Does it work for negative numbers?
A) Yes

Related programs :

Conclusion :

Reversing a number is a simple but very important concept in Python.

It helps you understand how digits and loops work together. instead of memorizing the code, focus on understanding the logic step by step.
Practice this problem with different numbers so that you gain confidence.

That's all for today friends.
Keep coding, keep learning.
DailyCodeHub

No comments:

Post a Comment